import Vue from "vue";
import VueRouter from "vue-router";
import db from "../utils/localstorage";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "login",
    component: () => import("../views/login"),
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login"),
  },
  {
    path: "/home",
    name: "home",
    component: () => import("../views/home")
  }
];

const router = new VueRouter({
  routes,
});


// 全局前置守卫，路由跳转前触发
router.beforeEach((to, from, next) => {
  const path = to.path;
  const token = db.get('TOKEN', '')
  if (path.indexOf('login') == -1) {
    if (token && token.length) {
      next()
    } else {
      next({ path: '/login' })
    }
  } else {
    next()
  }
})

// 全局后置守卫，路由跳转完成后触发
router.afterEach((to, from) => {
  if (from.path != '/login' && from.path != '/' && to.path == '/login') {
    window.location.reload();
  }
})
export default router;